<template>
  <div class="version admin-common-plate">
    <div class="current_v">当前移动端版本：{{ dbVersion }}</div>
    <div class="container">
      <div class="form">
        <el-form ref="form" :rules="rules" :model="form" label-width="100px">
          <el-form-item label="版本号" prop="version">
            <el-input
              v-model="form.version"
              :clearable="true"
              placeholder="请输入最新版本号"
              :disabled="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="上传apk" prop="downloadUrl">
            <input type="file" @change="uploadFile($event)" ref="file" hidden />
            <el-input
              v-model="form.downloadUrl"
              placeholder="请上传apk文件"
              disabled
              style="width: 76%"
            ></el-input>
            <el-button
              type="success"
              @click="$refs.file.click()"
              style="margin-left: 20px"
              >上传</el-button
            >
          </el-form-item>
          <el-form-item label="更新说明" prop="description">
            <el-input
              v-model="form.description"
              type="textarea"
              :autosize="{ minRows: 4, maxRows: 6 }"
              :clearable="true"
              placeholder="请输入此版本的更新说明（数据以回车进行分隔，注意回车时机）"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submit">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="history">
        <el-timeline :reverse="true" v-if="versionList.length > 0">
          <el-timeline-item
            :timestamp="formatDate(item.releaseDate)"
            placement="top"
            v-for="(item, index) in versionList"
            :key="index"
          >
            <el-card>
              <div class="history-version">版本{{ item.version }}</div>
              <div class="content">
                <span>更新内容：</span>
                <p
                  v-for="(item, index) in description(item.description)"
                  :key="index"
                >
                  {{ item }}
                </p>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        <el-skeleton :rows="6" animated v-else />
      </div>
    </div>
  </div>
</template>

<script>
import { getVersionList, releaseVersion } from "@/api/admin/version";
import { getVersion, uploadFile } from "@/api/common/common";
import { Message } from "element-ui";

export default {
  name: "VersionView",
  data() {
    return {
      form: {
        version: "",
        downloadUrl: "",
        description: "",
      },
      rules: {
        version: [
          { required: true, message: "请输入版本号", trigger: "blur" },
          {
            pattern: /^[0-9]+.[0-9]+.[0-9]+$/,
            message: "版本号格式不正确",
            trigger: "blur",
          },
        ],
        downloadUrl: [
          { required: true, message: "请上传apk文件", trigger: "change" },
        ],
        description: [
          { required: true, message: "请输入更新说明", trigger: "blur" },
        ],
      },
      // 数据库版版本
      dbVersion: "",
      versionList: [],
    };
  },
  computed: {
    version() {
      return process.env.VERSION;
    },
  },
  async created() {
    await this.getVersion();
    this.judgementVersion();
    this.getVersionList();
  },
  methods: {
    // 上传apk
    async uploadFile(file) {
      // 判断格式是否正确;
      const bool = this.verifyFormat(file.target.files[0]);
      if (!bool) {
        return;
      }
      // 上传到服务器;
      let formData = new FormData();
      // 拿到存在file中的文件存放到formData中
      formData.append("file", file.target.files[0]);
      const res = await uploadFile(formData);
      this.form.downloadUrl = res.data;
      // 清空文件
      this.$refs.file.value = "";
    },
    // 上传封面前校验格式
    verifyFormat(file) {
      const isJPG = file.type === "application/vnd.android.package-archive";
      if (!isJPG) {
        Message.error("上传文件只能是apk格式!");
        return false;
      }
      const prefix = file.name.split("_")[0];
      const isPrefix = prefix === "H55F3B59D";

      if (!isPrefix) {
        Message.error("安装包前缀不正确");
        return false;
      }
      return isJPG && isPrefix;
    },
    // 提交
    submit() {
      // 比较版本的大小
      const bool = this.compareVersion(this.version, this.dbVersion);
      if (bool === 0) {
        Message.error("暂无最新版本");
        return;
      }
      this.$refs.form.validate(async (v) => {
        if (v) {
          await releaseVersion(this.form);
          this.$refs.form.resetFields();
          this.getVersion();
          this.getVersionList();
        }
      });
    },
    // 获取版本信息
    async getVersion() {
      const res = await getVersion();
      this.dbVersion = res.data.version;
    },
    // 获取版本列表
    async getVersionList() {
      const res = await getVersionList();
      this.versionList = res.data;
    },
    /**
     * 比较版本号大小
     * @param v1 旧版本号
     * @param v2 新版本号
     */
    compareVersion(v1, v2) {
      // 将版本号字符串分割成数字数组
      const parts1 = v1.split(".").map(Number);
      const parts2 = v2.split(".").map(Number);

      // 补齐较短的版本号，使其长度相等
      const length = Math.max(parts1.length, parts2.length);
      parts1.length = length;
      parts2.length = length;

      // 逐个比较每个部分的数字
      for (let i = 0; i < length; i++) {
        if (parts1[i] > parts2[i]) {
          return -1;
        } else if (parts1[i] < parts2[i]) {
          return 1;
        }
      }
      return 0;
    },
    // 判断版本
    judgementVersion() {
      const bool = this.compareVersion(this.version, this.dbVersion);
      if (bool === 0) {
        this.form.version = "暂无最新版本";
      } else {
        this.form.version = this.version;
      }
    },
    // 格式化更新内容
    description(str) {
      return str.split("\n");
    },
    // 时间格式判断
    padZero(num) {
      return num < 10 ? "0" + num : num;
    },
    // 时间格式化
    formatDate(timeArray) {
      if (!timeArray) return "暂无时间";
      let year = timeArray[0];
      let month = this.padZero(timeArray[1]);
      let day = this.padZero(timeArray[2]);
      return `${year}-${month}-${day}`;
    },
  },
};
</script>

<style lang="less" scoped>
.version {
  .current_v {
    margin: 20px;
    padding-bottom: 10px;
    font-size: 20px;
    border-bottom: 1px solid #e0e0e0;
  }
  .container {
    display: flex;
    .form {
      width: 500px;
    }
    .history {
      flex: 1;
      margin-left: 50px;
      padding-right: 20px;
      max-height: 500px;
      overflow-y: auto;
      .history-version {
        margin: 0 20px 10px;
        font-size: 18px;
        font-weight: 600;
      }
      .content {
        margin: 0 20px;
        span {
          display: inline-block;
          margin-bottom: 6px;
        }
        p {
          line-height: 1.8;
        }
      }
    }
  }
}
/* 针对 Webkit 内核的浏览器（如 Chrome 和 Safari） */
::-webkit-scrollbar {
  width: 6px; /* 设置滚动条的宽度 */
}

::-webkit-scrollbar-track {
  background: #f1f1f1; /* 设置滚动条轨道的背景颜色 */
}

::-webkit-scrollbar-thumb {
  background: #ccc; /* 设置滚动条滑块的颜色 */
  border-radius: 4px; /* 设置滚动条滑块的圆角 */
}

::-webkit-scrollbar-thumb:hover {
  background: #555; /* 设置鼠标悬停在滚动条滑块上时的颜色 */
}
</style>